﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';

    // 自定义验证
    var checkInterval = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('请填时间间隔'))
        }
        if (!Number.isInteger(value)) {
            return callback(new Error('间隔必须为整数'));
        }
        callback();
    }

    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            timeIntervalPermission: true, // 能进到本页面，就是true
            timeIntervalCreatePermission: false,
            timeIntervalEditPermission: false,
            timeIntervalDeletePermission: false,
            timeIntervalDisablePermission: false,
            timeIntervalBatchCreatePermission: false,

            schedule: null,
            deviceType: null,
            department: null,
            filterName: '',
            dialogVisible: false,
            batchCreatVisible: false,
            dialogTitle: '新建时段',
            actionType: '新建',
            tableData: [],
            selectedRows: [],

            currentPage: 1,
            totalCount: 0,
            pageSize: 10,

            formLabelWidth: '80px',
            selectedRows: null,   // 当前选中行集合

            // 当前排班计划表
            timeInterval: {
                id: null,
                name: null,
                code: null,
                isActive: null,
                scheduleId: null,
                schedule: null,
                order: 0,
                startTime: null,
                endTime: null
            },

            // 批量生成模型
            batchModel: {
                startTime: null,
                endTime: null,
                interval: 30,
                options: [
                    {
                        lable: 30,
                        value:30
                    },
                    {
                        label: 60,
                        value: 60
                    }
                ]
            },
            valueFormat:'HH:mm',
            timePickerFormat: 'HH:mm a',

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                startTime: [
                    { required: true, message: '请输入开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, message: '请输入结束时间', trigger: 'blur' }
                ]
            },

            batchRules: {
                startTime: [
                    { required: true, message: '请输入开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, message: '请输入结束时间', trigger: 'blur' }
                ],
                interval: [
                    { validator: checkInterval, trigger:'blur' }
                ]
            }
        },
        computed: {

        },
        watch: {

        },
        methods: {
            // 搜索
            search() {
                var vm = this;
                if (vm.filterName) {
                    vm.currentPage = 1;
                    vm.loadTableData();
                }
            },

            // 分页切换
            currentPageChange(val) {
                var vm = this;
                vm.currentPage = val;
                vm.loadTableData();
            },

            // 每页数据量切换
            pageSizeChange(val) {
                var vm = this;
                vm.pageSize = val;
                vm.currentPage = 1;
                vm.loadTableData();
            },

            // 获取排班计划
            getSchedule() {
                var vm = this;
                return new Promise(resolve => {
                    var sid = window.utils.getQuery('sid');
                    if (!sid) {
                        abp.message.error('未获取到sid参数');
                    }
                    else {
                        abp.ajax({
                            type: 'get',
                            url: `/api/schedule/get?id=${sid}`
                        }).then(res => {
                            if (res.code === 0) {
                                vm.schedule = res.data;
                                vm.department = vm.schedule.department;
                                vm.deviceType = vm.schedule.deviceType;
                                resolve();
                            }
                        })
                    }
                });
            },

            // 科室选中用户改变
            selectedRowsChange(val) {
                var vm = this;
                vm.selectedRows = val;
            },

            startTimeChange(val) {
                var vm = this;
                
                if (vm.timeInterval.endTime) {
                    vm.timeInterval.name = `${vm.timeInterval.startTime} - ${vm.timeInterval.endTime}`
                } else {
                    vm.timeInterval.name = `${vm.timeInterval.startTime} -`
                }
            },

            endTimeChange(val) {
                var vm = this;
                if (vm.timeInterval.startTime) {
                    vm.timeInterval.name = `${vm.timeInterval.startTime} - ${vm.timeInterval.endTime}`
                }
                else {
                    vm.timeInterval.name = `-${vm.timeInterval.endTime}`
                }
                var str = `00:00:00 - ${val}:59`
            },

            // 批量对话框开始时间改变
            batchStartTimeChange(val) {
                var vm = this;
                var str = `${val}:00 - 23:59:59`
                vm.batchEndTimePickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 批量对话框结束时间改变
            batchEndTimeChange(val) {
                var vm = this;
                var str = `00:00:00 - ${val}:59`
                vm.batchStartTimePockerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 加载表格数据(只在初始化时执行一次)
            loadTableData() {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/time-interval/get-list?sid=${vm.schedule.id}&filterName=${vm.filterName}&page=${vm.currentPage}&pageSize=${vm.pageSize}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.tableData = res.data.list;
                            vm.totalCount = res.data.total;
                            resolve();
                        }
                    });
                })
            },

            // 显示新建检查项目对话框
            showCreate() {
                var vm = this;
                vm.dialogTitle = '创建排班计划';
                vm.actionType = '创建';
                vm.timeInterval.order = 0;
                vm.timeInterval.isActive = true;
                vm.dialogVisible = true;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        if (!vm.timeInterval.name) {
                            vm.timeInterval.name = `${vm.timeInterval.startTime} - ${vm.timeInterval.endTime}`
                        };
                        vm.timeInterval.scheduleId = vm.schedule.id;
                        abp.ajax({
                            type: 'post',
                            url: `/api/timeInterval/submit-create?sid=${vm.schedule.id}`,
                            data: JSON.stringify(vm.timeInterval)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.resetForm();
                                vm.loadTableData();
                            }
                        });
                    }
                });
            },

            // 打开编辑窗口
            showEdit(id) {
                var vm = this;
                vm.dialogTitle = '编辑排班计划';
                vm.actionType = '编辑';
                vm.loadDetail(id).then(() => {
                    vm.dialogVisible = true;
                })
            },

            // 编辑提交
            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/timeInterval/submit-edit`,
                            data: JSON.stringify(vm.timeInterval)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadTableData();
                                vm.resetForm();
                            }
                        })
                    }
                });
            },

            save() {
                var vm = this;
                if (vm.actionType.includes('编辑')) {
                    vm.submitEdit();
                }
                else {
                    vm.submitCreate();
                }
            },

            // 打开批量生成对话框
            showBatchCreate() {
                var vm = this;
                vm.batchCreatVisible = true;
            },

            // 批量生成
            batchCreate() {
                var vm = this;
                vm.$refs['batchForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/time-interval/batch-create?sid=${vm.schedule.id}`,
                            data: JSON.stringify(vm.batchModel)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.currentPage = 1;
                                vm.resetBatchForm();
                                vm.loadTableData();
                            }
                        });
                    }
                });
            },

            // 加载检查项目详情
            loadDetail(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/timeInterval/get?id=${id}`
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.timeInterval = res.data;
                            resolve(res.data);
                        }
                    })
                });
            },

            // 加载当前权限
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('AppointManagerGroup.TimeInterval')) { // 检查项目管理权限
                        vm.timeIntervalPermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval.Create')) {// 新建检查项目权限
                            vm.timeIntervalCreatePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval.Edit')) { // 编辑检查项目权限
                            vm.timeIntervalEditPermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval.Delete')) { // 删除检查项目权限
                            vm.timeIntervalDeletePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval.Disable')) { // 同步数据权限
                            vm.timeIntervalDisablePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval.BatchCreate')) {
                            timeIntervalBatchCreatePermission = true;
                        }
                    }
                    resolve();
                });
            },

            disableToggle(row) {
                var vm = this;
                var confirmStr = '禁用预约时段';
                if (row.isActive) {
                    confirmStr = '启用预约时段';
                }
                abp.message.confirm(confirmStr)
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/timeInterval/toggle-disable?id=${row.id}`
                            }).then((res) => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadTableData();
                                }
                            })
                        }
                    })
            },

            // 删除多个
            deleteMany() {
                var vm = this;
                if (vm.selectedRows.length === 0) {
                    abp.notify.error('请选中时段！');
                }
                else {
                    abp.message.confirm('你将批量删除预约时段')
                        .then(confirmed => {
                            if (confirmed) {
                                var idList = vm.selectedRows.map(item => item.id);
                                abp.ajax({
                                    type: 'post',
                                    url: `/api/time-interval/delete-many`,
                                    data: JSON.stringify(idList)
                                }).then(res => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.loadTableData();
                                    }
                                });
                            }
                        })
                }
            },

            // 删除时间段
            deleteTimeInterval(id) {
                var vm = this;
                abp.message.confirm('你将删除预约时段')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'delete',
                                url: `/api/timeInterval/delete?id=${id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadTableData();
                                }
                            })
                        }
                    })
            },

            // 表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.timeInterval).forEach(key => {
                    vm.timeInterval[key] = null;
                });
            },

            // 批量生成 表单重置
            resetBatchForm() {
                var vm = this;
                vm.$refs['batchForm'].resetFields();
                vm.batchCreatVisible = false;
                vm.batchModel.startTime = null;
                vm.batchModel.endTime = null;
                vm.batchStartTimePockerOption = {
                    selectableRange: '00:00:00-23:59:59',
                    format: 'HH:mm:ss a'
                };
                vm.batchEndTimePickerOption = {
                    selectableRange: '00:00:00-23:59:59',
                    format: 'HH:mm:ss a'
                };
                vm.batchModel.interval = 30;
            },

            // 初始化
            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.getSchedule().then(() => {
                            vm.loadTableData();
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});